<template>
  <div class="content">
    <el-table :data="songsData" stripe style="width: 100%" size="medium" @row-dblclick="play"
      :row-class-name="tableRowClassName" :row-style="selectedstyle" @row-contextmenu="rightList">
      <el-table-column type="index"></el-table-column>
      <el-table-column width="40">
        <div class="el-icon-video-play"></div>
      </el-table-column>

      <el-table-column prop="name" label="音乐标题">
        <template slot-scope="scope">
          <div class="musicTitle">
            <div class="rowName">
              {{ scope.row.name }}
            </div>
            <div v-if="scope.row.fee === 1 && scope.row.fee === 8" class="vip">
              VIP
            </div>
            <div>
              <el-image :src="require('../../assets/image/SQ.jpg')" v-if="scope.row.fee === 8"></el-image>
            </div>
            <div v-if="scope.row.originCoverType === 2" class="oringin">
              翻唱
            </div>
            <div v-if="scope.row.mv !== 0" class="mv" @click="playMv(scope.row)">
              MV
            </div>
          </div>
        </template>
      </el-table-column>

      <el-table-column prop="ar.name" label="歌手">
        <template slot-scope="scope">
          <div class="nameBox">
            <div v-for="(item, i) in scope.row.ar" :key="i">
              <el-tooltip class="item" effect="dark" :content="scope.row.ar[i].name" placement="top">
                <div @click="getArt(scope.row.ar[i].id)" class="art">
                  {{ scope.row.ar[i].name }}
                </div>
              </el-tooltip>
            </div>
          </div>
        </template>
      </el-table-column>

      <el-table-column prop="al.name" label="专辑">
        <template slot-scope="scope">
          <el-tooltip class="item" effect="dark" :content="scope.row.al.name" placement="top">
            <div @click="getAlb(scope.row.al)" class="art">
              {{ scope.row.al.name }}
            </div>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column prop="dt" label="时长">
        <template slot-scope="scope">
          {{ Math.floor(scope.row.dt / 1000) | timeFormat }}
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页器开始 -->
    <div class="block">
      <el-pagination @current-change="handleCurrentChange" :page-size="30" layout="total , prev, pager, next"
        :total="count">
      </el-pagination>
    </div>
    <div class="loading" v-if="show === true">
      <i class="el-icon-loading"></i>
    </div>
    <Memu />
  </div>
</template>

<script>
import { mapState, mapActions } from 'vuex';
import debounce from "@/utils/debounce.js";
export default {
  components: {
    Memu: () => import('../../components/rightMemu.vue'),
  },
  computed: {
    ...mapState(['seachSong', 'seachSongItem', 'nowPlaySong', 'preSong']), // 读取VUEX中的状态
  },
  mounted() {
    this.songsData = this.seachSong.seachSong;
    if (this.seachSongItem !== null) {
      this.count = this.seachSongItem.seachSongItem.songCount;
    }

    if (this.nowPlaySong !== null) {
      this.songId = this.nowPlaySong.songId;
    }
  },
  watch: {
    seachSong(newVal, oldVal) {
      this.getIndex = '';
      this.songsData = newVal.seachSong;
    },
    seachSongItem(newVal, oldVal) {
      this.count = newVal.seachSongItem.songCount;
    },
    preSong(newVal, oldVal) {
      this.getIndex = newVal.preSong;
      this.play(this.songsData[this.getIndex]);
    },
    nowPlaySong(newVal, oldVal) {
      this.songId = newVal.songId;
    },
  },
  data() {
    return {
      songsData: null,
      getIndex: '',
      keywords: '',
      limit: 30, // 单页数量
      offset: 0, // 页数
      count: 0,
      show: false,
      songId: '',
      row: null,
      rightShow: false,
    };
  },
  methods: {
    ...mapActions([
      'saveNowSongCount',
      'saveNowSong',
      'saveSongList',
      'saveAlbumData',
      'clickPlay',
      'saveNowId',
      'saveNowSongCount',
      'saveMVurl',
      'saveResMv',
      'saveMvBes',
      'saveArtistsItem',
      'saveNowRow',
    ]),

    async play(row) {
      const e = localStorage.getItem('cookie');
      const title = row.name;
      const arr = row.ar.map((item) => {
        return item.name;
      });
      const artist = arr.join();
      const pic = row.al.picUrl;
      this.songId = row.id;
      this.getIndex = row.row_index;
      this.$api.songUrl({ cookie: e, id: row.id, cookie: localStorage.getItem('cookie') }).then((ret) => {
        this.songId = row.id;
        if (ret.data[0].url !== null) {
          this.saveNowSong({
            id: this.getIndex,
            title,
            artist,
            src: ret.data[0].url,
            pic,
            songId: this.songId,
          });
          this.clickPlay({ ifPlay: false });
          this.$api.scrobble({ id: this.songId, cookie: e, sourceid: row.al.id, timestamp: this.$utils.timestamp() })
          this.saveNowSongCount({ nowSongCount: this.songsData });
        } else {
          this.$message.error('该歌曲暂时无法播放!!!');
        }
      });
    },

    tableRowClassName({ row, rowIndex }) {
      row.row_index = rowIndex;
    },

    // 翻页
    handleCurrentChange: debounce(function (e) {
      this.keywords = window.sessionStorage.getItem('keywords');
      this.offset = (e - 1) * 30;
      if (this.offset > this.count) {
        this.offset = (e - 1) * 30 - (this.offset - this.count) - 1;
        this.getData();
      } else {
        this.getData();
      }
       
    }, 1000),

    // 获取数据
    async getData() {
      this.$api
        .search({
          keywords: this.keywords,
          limit: this.limit,
          offset: this.offset,
          cookie: localStorage.getItem('cookie'),
        })
        .then((ret) => {
          this.songsData = ret.result.songs;
          this.saveSongList({ songList: ret.result.songs });
        });
    },

    // 设置行的颜色
    selectedstyle({ row, rowIndex }) {
      if (this.songId === row.id) {
        return {
          color: '#ec4141',
        };
      }
    },

    // 右键菜单
    rightList(row, column, event) {
      window.sessionStorage.setItem('getIndex', this.getIndex);
      this.saveNowRow({ nowRow: row })
      this.row = row
      this.rightShow = true
      document.querySelector('.list').style.left = `${event.clientX}px`
      document.querySelector('.list').style.top = `${event.pageY}px`
      const top = parseInt(document.querySelector('.list').style.top)
      const height = document.querySelector('.list').offsetHeight
      if (top + height >= event.screenY) {
        document.querySelector('.list').style.top = `${event.screenY - height - 60}px`
      }
    },


    // 关闭右键菜单
    closeRight() {
      this.rightShow = false
    },

    // 跳转到歌手页面
    getArt(e) {
      this.show = true;
      window.sessionStorage.setItem('artists', e);
      this.$router.push(`/artistsPage?id=${e}`);
    },

    // 跳转到专辑页面
    async getAlb(e) {
      this.show = true;
      this.$api.album({ id: e.id, cookie: localStorage.getItem('cookie') }).then((ret) => {
        window.sessionStorage.setItem('album', e.id);
        this.saveAlbumData({ albumData: ret });
        this.$router.push(`/albumPage?id=${e.id}`);
      });
    },

    // 点击播放MV
    playMv(e) {
      // 获取到MV的地址
      this.$api.mvUrl({ id: parseInt(e.mv), cookie: localStorage.getItem('cookie') }).then((ret) => {
        this.saveMVurl({ mvUrl: ret.data.url });
      });
      this.getArtists(e.ar[0].id);
      this.getResMv(e.mv);
      this.getItem(e.mv);
    },

    // 获取相似MV
    async getResMv(e) {
      this.$api.simiMv({ mvid: e, cookie: localStorage.getItem('cookie') }).then((ret) => {
        this.saveResMv({ resMv: ret });
      });
    },

    // 获取MV基础信息
    async getItem(e) {
      this.loading = true;
      this.$api.mvDetail({ mvid: e, cookie: localStorage.getItem('cookie') }).then((ret) => {
        this.saveMvBes({ mvBes: ret });
        this.$router.push(`/mvPlay?id=${e}`);
      });
    },

    // 获取MV作者
    async getArtists(e) {
      window.sessionStorage.setItem('artists', e);
      this.$api.arDetail({ id: e, cookie: localStorage.getItem('cookie') }).then((ret) => {
        this.saveArtistsItem({ artistsItem: ret.data });
      });
    },
  },
};
</script>

<style scoped>
.content {
  margin-bottom: 40px;
}

.more {
  cursor: pointer;
}

.nameBox {
  display: flex;
}

.art {
  cursor: pointer;
  width: 60px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.loading {
  position: absolute;
  width: 100%;
  height: 100%;
  top: 0;
}

.rowName {
  width: 150px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.el-icon-loading {
  position: fixed;
  font-size: 50px;
  left: 50%;
  top: 50%;
  color: #ec4141;
}

.musicTitle {
  display: flex;
  align-items: center;
}

.el-image {
  display: flex;
  align-items: center;
  margin-right: 8px;
}

.vip {
  width: 27px;
  height: 15px;
  border: 1px solid orangered;
  font-size: 10px;
  color: orangered;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 2px;
  margin-right: 8px;
}

.oringin {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 30px;
  height: 15px;
  border: 1px solid rgb(90, 86, 86);
  color: rgb(87, 75, 75);
  border-radius: 2px;
  font-size: 10px;
  margin-right: 8px;
}

.mv {
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 27px;
  height: 15px;
  border: 1px solid #ec4141;
  color: #ec4141;
  border-radius: 2px;
  font-size: 10px;
}
</style>
